<template>
  <div>
    <div class="historys">
      <span class="searchHis">搜索历史</span>
      <span>
        <van-icon
          name="delete"
          size="20"
          @click="del"
        />
      </span>
    </div>
    <!-- 历史列表 -->
    <div class="history-list">
      <span
        class="history-item"
        v-for="(item,index) in historyy"
        :key="index"
        @click="jump(item)"
        @touchstart='touchstartFn(index)'
        @touchmove='touchmoveFn'
        @touchend='touchendFn'
        @selectstart.prevent
      >{{item}}</span>
    </div>
  </div>
</template>

<script>
import { Dialog } from 'vant';
// 导入局部组件必须在scrip里面导入,在App里面导入
export default {
  // 组件名称
  name: 'his',
  // 组件参数 接收来自父组件的数据
  props: {
    val: { type: String }
  },
  // 接收局部注册的组件
  components: { [Dialog.Component.name]: Dialog.Component, },
  // 组件数据
  data () {
    return {
      // history: ['API', 'java', 'css', '前端', '后台接口', 'python'],
      historyy: [],
      timeOut: null
    }
  },
  methods: {
    // 长按
    touchstartFn (index) {
      this.timeOut = setTimeout(() => {
        // console.log(index);
        Dialog.confirm({
          title: '确定删除吗?',

        })
          .then(() => {
            this.historyy.splice(index, 1)
            window.localStorage.setItem('history', JSON.stringify(this.historyy))

          })
          .catch(() => {
            // on cancel
          });

      }, 800);
    },
    // 移动取消定时器和不到时间
    touchmoveFn () {
      clearTimeout(this.timeOut)
    },
    touchendFn () {
      clearTimeout(this.timeOut)
    },
    jump (vale) {
      this.$router.push(`/search/${vale}`)
    },
    del () {
      Dialog.confirm({
        title: '确定删除吗?',

      })
        .then(() => {
          this.historyy = []
          window.localStorage.removeItem('history')
        })
        .catch(() => {
          // on cancel
        });

    }
  },
  watch: {
    val () {
      if (this.val !== '') {
        this.historyy.push(this.val)
        window.localStorage.setItem('history', JSON.stringify(this.historyy))
        this.historyy = JSON.parse(window.localStorage.getItem('history'))
      }
    }
  },
  //打开页面就从本地读取来渲染
  activated () {
    this.historyy = JSON.parse(window.localStorage.getItem('history')) || []
  },

}
</script>
<style lang='less' scoped>
.historys {
  display: flex;
  justify-content: space-between;
  align-items: baseline;
  margin: 0 10px;
  border-bottom: 1px solid #ccc;
}

.searchHis {
  font-size: 14px;
}

.search-icon {
  font-size: 16px;
  line-height: inherit;
}

.history-list {
  padding: 0 10px;
  .history-item {
    display: inline-block;
    font-size: 12px;
    padding: 8px 14px;
    background-color: #efefef;
    margin: 10px 8px 0px 8px;
    border-radius: 10px;
  }
}
</style>
